package com.neusoft.config;

import com.neusoft.model.PageModel;
import com.neusoft.model.PageSearch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Aspect
@Component
public class PagePlugin {


    @Pointcut("@annotation(com.neusoft.config.Pagination)")
    public void page() {
    }

    @Around("page()")
    public PageModel around(ProceedingJoinPoint pjp) {
        Object[] args = pjp.getArgs();
        PageSearch pageSearch = (PageSearch) args[0];
        try {
            int pageNum = pageSearch.getPageNum();
            int pageSize = pageSearch.getPageSize();
            PageModel pageModel = new PageModel(pageNum, pageSize);
            List list = (List) pjp.proceed(args);
            pageModel.setTotal(list.size());
            int fromIndex = (pageNum - 1) * pageSize;
            int toIndex = pageNum * pageSize;
            if (list.size() > fromIndex) {
                if (list.size() > toIndex) {
                    list = list.subList(fromIndex, toIndex);
                } else {
                    list = list.subList(fromIndex, list.size());
                }
            } else {
                list = Collections.emptyList();
            }
            pageModel.setRecords(list);
            return pageModel;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        Integer[] ids = new Integer[]{1, 2, 3, 4};
        System.out.println(Arrays.asList(ids).subList(1, 4));
    }
}
